package org.or5e.plugin.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import org.or5e.core.BaseObject;
import org.or5e.plugin.core.vo.ITunesTrack;

public class ITunesFileCopy extends BaseObject{
	public void copyFile(ITunesTrack track, String index) {
		String sourceURL = track.getTrackLocation();
		sourceURL = sourceURL.replaceAll("%20", " ").replaceAll("file://localhost/", "");

		String outputPath = getProperties("sync-folder-music");
		String fileName = index+outputPath+sourceURL.substring(sourceURL.lastIndexOf("/")+1);
		debug("Copying File: "+sourceURL + " To: "+fileName);
		try {
			FileInputStream inputStream = new FileInputStream(sourceURL);
			FileOutputStream outputStream = new FileOutputStream(fileName);
			FileChannel inChannel = inputStream.getChannel();
			FileChannel outChannel = outputStream.getChannel();
			inChannel.transferTo(0, inChannel.size(), outChannel);
			inChannel.close();
			outChannel.close();
			inputStream.close();
			outputStream.close();
			track.setTrackLocation(fileName);
		} catch (FileNotFoundException e) {
			//e.printStackTrace();
			debug(e.getMessage());
		} catch (IOException e) {
//			e.printStackTrace();
			debug(e.getMessage());
		}
	}
	@Override public String getName() {
		return "ITunesFileCopy";
	}
}